package com.mchsdk.paysdk.server;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mchsdk.paysdk.activity.MCPacksActivity;
import com.mchsdk.paysdk.activity.MCPersonalInfoActivity;
import com.mchsdk.paysdk.activity.MCSocialActivity;
import com.mchsdk.paysdk.bean.PersonalCenterModel;
import com.mchsdk.paysdk.receive.HomeKeyEventBroadCastReceiver;
import com.mchsdk.paysdk.utils.DeviceInfo;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.ToastUtil;


public class MCHFloatService extends Service {
    /**
     * 打印日志
     */
    private final String TAG = "MCHFloatService";

    /**
     * 悬浮窗显示时间
     */
    private final static int FLOATING_SHOW_TIME = 3 * 1000;

    /**
     * 悬浮窗滑动此像素后，响应滑动事件
     */
    private final static int FLOATING_MOVE_DISTANCE = 5;

    /**
     * 当前窗口
     */
    WindowManager wm = null;
    /**
     * 当前窗口布局
     */
    LayoutParams wmParams = null;
    /**
     * 当前窗口的页面
     */
    View view;
    /**
     * 相对View的坐标的开始坐标
     */
    private float mTouchStartX;
    private float mTouchStartY;
    /**
     * 获取相对屏幕的坐标
     */
    private float x;
    private float y;
    /**
     * 悬浮窗初始位置
     */
    private float StartX;
    private float StartY;

    /**
     * 悬浮窗的状态
     */
    // private int state;

    /**
     * 手机状态栏高度
     */
    private int deviceTopBarHeight;
    /**
     * 手机屏幕的高度宽度
     */
    private int height;
    private int width;

    /**
     * 悬浮窗是否显示
     */
    private boolean floatingIsShow;

    /**
     * 悬浮窗按钮列表
     */
    RelativeLayout llMenuList;

    /**
     * 渠道标识
     */
    TextView txtChannel;
    HomeKeyEventBroadCastReceiver homeReceiver;
    /**
     * 手机版本
     */
    final int version = Build.VERSION.SDK_INT;
    /**
     * 悬浮窗延时消失
     */
    Handler floatHandler = new Handler();

    Runnable floatRunable = new Runnable() {

        @Override
        public void run() {
            if (llMenuList.isShown()) {
                hideFloating();
            }
        }
    };

    Runnable backgroundRunnable = new Runnable() {

        @Override
        public void run() {
            // if (Math.abs(y)< height / 3 && Math.abs(y) <
            // Math.abs(x)&&Math.abs(y)<(width-Math.abs(x))) {// 上移
            // y = -deviceTopBarHeight;
            // txtChannel.setY(-50);
            // } else if (x < width / 3) {// 左移
            // x = 0;
            // y-=deviceTopBarHeight;
            // txtChannel.setX(-50);
            // } else if (x > (width * (2 / 3))) {// 右移动
            // x = width;
            // y-=deviceTopBarHeight;
            // txtChannel.setX(50);
            // }
            if (Math.abs(x) < width / 2) {
                x = 0;
                y -= deviceTopBarHeight;
                txtChannel.setX(-txtChannel.getWidth() / 2);
            } else {
                if (width > height) {
                    x = width;
                } else {
                    x = height;
                }
                y -= deviceTopBarHeight;
                txtChannel.setX(txtChannel.getWidth() / 2);
            }
            updateViewPosition();
            txtChannel.setBackgroundResource(MCHInflaterUtils.getDrawable(
                    MCHFloatService.this, "mch_float_ico_h"));
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        MCLog.w(TAG, "fun#onCreate--------");
        super.onCreate();
        view = LayoutInflater.from(this).inflate(
                MCHInflaterUtils.getLayout(this, "floating_mch_menu"), null);
        createView();
        initData();
        initView();
    }

    private void initData() {
        floatingIsShow = false;
    }

    private void initView() {
        if (null == view) {
            MCLog.w(TAG, "fun#initView view is null");
            return;
        }
        llMenuList = (RelativeLayout) view.findViewById(MCHInflaterUtils
                .getControl(this, "ll_mch_menu_list"));
        llMenuList.setVisibility(View.GONE);

        txtChannel = (TextView) view.findViewById(MCHInflaterUtils.getControl(
                this, "txt_mch_channel_name"));
        txtChannel.setBackgroundResource(MCHInflaterUtils.getDrawable(this,
                "mch_float_ico"));
        txtChannel.setText("1");
        txtChannel.setTextColor(Color.TRANSPARENT);
        LinearLayout llPacks = (LinearLayout) view
                .findViewById(MCHInflaterUtils.getControl(this,
                        "ll_mch_floating_pack"));
        llPacks.setOnClickListener(choiceListener);

        LinearLayout llPersonal = (LinearLayout) view
                .findViewById(MCHInflaterUtils.getControl(this,
                        "ll_mch_floating_personal"));
        llPersonal.setOnClickListener(choiceListener);

        LinearLayout llSocial = (LinearLayout) view.findViewById(MCHInflaterUtils.getControl(this, "ll_mch_floating_social"));
        llSocial.setOnClickListener(choiceListener);
        homeReceiver = new HomeKeyEventBroadCastReceiver();
        registerReceiver(homeReceiver, new IntentFilter(
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    /**
     * 个人中心和礼包监听
     */
    OnClickListener choiceListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (null == PersonalCenterModel.getInstance().channelAndGame
                    || TextUtils
                    .isEmpty(PersonalCenterModel.getInstance().channelAndGame
                            .getAccount())) {
                ToastUtil.show(getApplicationContext(), "请登录");
                return;
            }
            Intent pack = null;
            if (id == MCHInflaterUtils.getControl(getApplicationContext(),
                    "ll_mch_floating_pack")) {
                pack = new Intent(MCHFloatService.this, MCPacksActivity.class);
            } else if (id == MCHInflaterUtils.getControl(
                    getApplicationContext(), "ll_mch_floating_personal")) {
                pack = new Intent(MCHFloatService.this,
                        MCPersonalInfoActivity.class);
            } else if (id == MCHInflaterUtils.getControl(getApplicationContext(), "ll_mch_floating_social")) {
                pack = new Intent(MCHFloatService.this, MCSocialActivity.class);
            }
            pack.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(pack);
        }
    };

    @Override
    public void onStart(Intent intent, int startId) {
        startForeground(0, null);
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(homeReceiver);
        wm.removeView(view);
        super.onDestroy();
    }

    private void createView() {
        if (null == view) {
            MCLog.w(TAG, "fun#createView view is null");
            return;
        }
        // 获取WindowManager
//		wm = (WindowManager) getApplicationContext().getSystemService("window");
        wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();// 手机屏幕的高度
        height = wm.getDefaultDisplay().getHeight();// 宽度
        deviceTopBarHeight = DeviceInfo
                .getStatusBarHeight(MCHFloatService.this);// 手机自带任务栏的高度
        // 设置LayoutParams(全局变量）相关参数
        wmParams = new LayoutParams();
        // wmParams.type = 2002; // 这里的2002表示系统级窗口
        // android版本
        //解决Android 7.1.1起不能再用Toast的问题（先解决crash）
        if (Build.VERSION.SDK_INT > 24) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Android 8.0上不能再用TYPE_PHONE的问题
                wmParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                wmParams.type = LayoutParams.TYPE_PHONE;
            }
        } else {
            wmParams.type = LayoutParams.TYPE_TOAST;
        }
        // 全屏可以到顶部
        // wmParams.type=LayoutParams.TYPE_PHONE;
        wmParams.flags |= 8;
        wmParams.gravity = Gravity.LEFT | Gravity.TOP; // 调整悬浮窗口至左上角
        // 以屏幕左上角为原点，设置x、y初始值
        wmParams.x = 0;
        wmParams.y = 0;
        // 设置悬浮窗口长宽数据
        wmParams.width = LayoutParams.WRAP_CONTENT;
        wmParams.height = LayoutParams.WRAP_CONTENT;
        wmParams.format = 1;
        wm.addView(view, wmParams);

        deviceTopBarHeight = DeviceInfo
                .getStatusBarHeight(MCHFloatService.this);

        view.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 获取相对屏幕的坐标，即以屏幕左上角为原点
                x = event.getRawX();
                y = event.getRawY() - deviceTopBarHeight;// 解决每次点击下滑问题
                // MCLog.i(TAG, "fun#onTouch currX:" + x + "====currY:" + y);

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:/* 按下 */
                        // state = MotionEvent.ACTION_DOWN;
                    /* 设置悬浮窗从自身左边0的位置开始显示；如果设置成-50，悬浮穿左移动50，但是只显示原来位置的东西 */
                        txtChannel.setX(0);
                        txtChannel.setY(0);
                    /* 开始时候，悬浮窗的位置为屏幕左上角的位置 */
                        StartX = x;
                        StartY = y;
                        // 获取相对View的坐标，即以此View左上角为原点
                        mTouchStartX = event.getX();
                        mTouchStartY = event.getY();
                        // MCLog.i(TAG, "Action#ACTION_DOWN mTouchStartX:" +
                        // mTouchStartX +
                        // "====mTouchStartY:" + mTouchStartY);
//					MCLog.i(TAG, "按下");
                        break;
                    case MotionEvent.ACTION_MOVE:/* 移动 */
                        // MCLog.e(TAG, "fun#onTouch ACTION_MOVE:");
                        // state = MotionEvent.ACTION_MOVE;
                        if (Math.abs(x - StartX) > FLOATING_MOVE_DISTANCE
                                || Math.abs(y - StartY) > FLOATING_MOVE_DISTANCE) {
                            hideFloating();
                            txtChannel.setBackgroundResource(MCHInflaterUtils
                                    .getDrawable(MCHFloatService.this,
                                            "mch_float_ico"));
                            setChannelBackground();

                        }
                        updateViewPosition();
                        // MCLog.i(TAG, "移动");
                        break;
                    case MotionEvent.ACTION_UP:/* 抬起 */
                        // MCLog.e(TAG, "fun#onTouch state:" + state);
                        if (Math.abs(x - StartX) < FLOATING_MOVE_DISTANCE
                                && Math.abs(y - StartY) < FLOATING_MOVE_DISTANCE) {
                            contralFloating();
                        }
                        // state = MotionEvent.ACTION_UP;
                        updateViewPosition();
                        mTouchStartX = mTouchStartY = 0;
//					MCLog.i(TAG, "抬起");
                        break;
                }
                // MCLog.i(TAG, "x = " + x + " y = " + y);
                // MCLog.i(TAG, "startx = " + StartX + " starty = " + StartY);
                // MCLog.i(TAG, "mTouchStartX = " + mTouchStartX);
                // MCLog.i(TAG," mTouchStartY = " + mTouchStartY);
                return false;
            }
        });
    }

    /**
     * 隐藏悬浮窗
     */
    private void hideFloating() {
        if (llMenuList.isShown()) {
            floatingIsShow = false;
            llMenuList.setVisibility(View.GONE);
            floatHandler.removeCallbacks(backgroundRunnable);
            floatHandler.postDelayed(backgroundRunnable, FLOATING_SHOW_TIME);
            if (null != floatHandler && null != floatRunable) {
                floatHandler.removeCallbacks(floatRunable);
            }
        }
    }

    /**
     * 显示悬浮窗
     */
    private void showFloating() {
        if (!llMenuList.isShown()) {
            floatingIsShow = true;
            llMenuList.setVisibility(View.VISIBLE);
            txtChannel.setBackgroundResource(MCHInflaterUtils.getDrawable(
                    MCHFloatService.this, "mch_float_ico"));
            setChannelBackground();
            if (null != floatHandler && null != floatRunable) {
                floatHandler.postDelayed(floatRunable, FLOATING_SHOW_TIME);
            }
        }
    }

    /**
     * 控制悬浮窗
     */
    private void contralFloating() {
        // MCLog.e(TAG, "fun#contralFloating floatingIsShow:" + floatingIsShow);
        if (floatingIsShow) {
            hideFloating();
        } else {
            showFloating();
        }
    }

    /**
     * 更新悬浮窗口的位置
     */
    private void updateViewPosition() {
        if (version >= 19) {
            // 4.4以上显示悬浮窗不用配置权限,解决小米，魅族不显示悬浮窗
        } else {
            y = y + deviceTopBarHeight;
        }
        // 更新浮动窗口位置参数
        try {
            wmParams.x = (int) (x - mTouchStartX);
            wmParams.y = (int) (y - mTouchStartY);
            wm.updateViewLayout(view, wmParams);
        } catch (Exception e) {
            Log.e(TAG, "fun # updateViewPosition " + e);
        }
    }

    private void setChannelBackground() {
        floatHandler.removeCallbacks(backgroundRunnable);
        floatHandler.postDelayed(backgroundRunnable, FLOATING_SHOW_TIME);
    }
}
